﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;
using DataEntity;
using System.Collections.ObjectModel;
using DS40xxSDK;
using System.IO;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using EDSDKLib;
using System.Diagnostics;

namespace SWA_View
{
     
    public partial class MainForm : Form
    {
        private delegate void SetButtonEnableCallback();
        private delegate void SetLableCallback();

        private delegate void SetRecStatusLightPicCallback();

        private delegate void SetlblTimeElapsedCallback();

        #region streamDrctRdCallBack
        private STREAM_DIRECT_READ_CALLBACK streamDrctRdCallBack =
            delegate(int ChNum, IntPtr DataBuf, int Length, FrameType_t FrameType, IntPtr context)
            {
                MainForm mainWindow = (MainForm)MainForm.FromHandle(context);

                //string SaveDir = mainWindow.DataDir.FullName + @"\" + mainWindow.PrjBrief.PrjNo;
                //Debug.WriteLine("EncodeCh:{0},DataLen:{1}, FrameType:{2}, context:{3}", ChNum, Length, FrameType,
                //context.ToString());

                FileStream fs = null;

                try
                {
                    if (!Directory.Exists(mainWindow._VideoPicPath))
                    {
                        Directory.CreateDirectory(mainWindow._VideoPicPath);
                    } 
                    fs = new FileStream(mainWindow._VideoPicPath + (ChNum + 1).ToString() + ".avi", FileMode.Append, FileAccess.Write);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("不要在录像时访问文件夹！");
                    //Debug.WriteLine("Don't touch the video dir.");

                }
                finally
                {
                    byte[] buf = new byte[Length];
                    Marshal.Copy(DataBuf, buf, 0, Length);
                    if (fs != null)
                    {
                        fs.Write(buf, 0, Length);
                        fs.Close();
                    }
                }


                return 0;
            };
        #endregion

        private int _ProjectID = 0;
        bool bStopped = false;
        public MainForm(int id)
        {
            InitializeComponent();
            _ProjectID = id;
            ExItemsList.Items.Clear();
            
            Expert.CollectionChanged += (sender, e) =>
            {
                ExItemsList.Items.Clear();
                
                foreach (var c in Expert)
                {
                    var item = new Telerik.WinControls.UI.RadListDataItem() { Text = c.DataCombination, Value = c };
                    c.PropertyChanged -= new PropertyChangedEventHandler(c_PropertyChanged);
                    c.PropertyChanged += new PropertyChangedEventHandler(c_PropertyChanged);
                    if (c.IsFinished.Equals("是") && c.IsIng.Equals("否"))
                    {
                        item.Image = new Bitmap(Properties.Resources._007);
                    }
                    else if (c.IsFinished.Equals("否") && c.IsIng.Equals("是"))
                    {
                        item.Image = new Bitmap(Properties.Resources._006);
                    }
                    else
                    {
                        item.Image = new Bitmap(Properties.Resources._004);
                    }
                    ExItemsList.Items.Add(item);
                }
            };
            this.Load += new EventHandler(MainForm_Load);
        }

        void c_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("IsFinished") || e.PropertyName.Equals("IsIng"))
            {
                ExperimentCombinationEntity entity = sender as ExperimentCombinationEntity;
                if (entity != null && entity.IsIng.Equals("是") && entity.IsFinished.Equals("否"))
                {
                    _VideoPicPath = this.GetDirectory() + "Vedio\\";
                    _picPath = this.GetDirectory() + "Photo\\";
                }
            }
        }
        ProjectEntity pe = null;
        private string _VideoPicPath = null;
        DateTime _startTime = DateTime.Now;
        private static DataTypes.TestCombinationInfo _currentTestCombInfo;// = new DataTypes.TestCombinationInfo();
        static public DataTypes.TestCombinationInfo CurrentTestCombInfo
        {
            get { return _currentTestCombInfo; }
            set { _currentTestCombInfo = value; }
        }
        private List<DataTypes.TestCombinationInfo> _testCombinationInfos;
        public List<DataTypes.TestCombinationInfo> TestCombinationInfos
        {
            get { return _testCombinationInfos; }
            set { _testCombinationInfos = value; }
        }

        
        void MainForm_Load(object sender, EventArgs e)
        {
            ProjectModel pm = new ProjectModel();
            pe = pm.GetProjectEntity("ID=" + _ProjectID).FirstOrDefault();
            label_client.Text = pe.Client;
            label_ModelNo.Text = pe.ModelNo;
            label_projectNo.Text = pe.ProjectNo;
            label_Rate.Text = pe.Rate;
            label_ShipType.Text = pe.ShipType;
            //groupBox1.MouseDoubleClick += new MouseEventHandler(groupBox1_MouseDoubleClick);
            
            //groupBox2.MouseDoubleClick += new MouseEventHandler(groupBox1_MouseDoubleClick);
            //groupBox3.MouseDoubleClick += new MouseEventHandler(groupBox1_MouseDoubleClick);
            //groupBox4.MouseDoubleClick += new MouseEventHandler(groupBox1_MouseDoubleClick);
            int count = InitCamera(0);
            if (count > 0)
            {
                InitCamera(1);
                InitCamera(2);
            }
            //List<string> items = new List<string>()
            //{
            //    "13,14,16",
            //    "13,14,17",
            //    "13,14,18",
            //    "13,14,19",
            //};
            //foreach (var c in items)
            //{
            //   ExItemsList.Items.Add(new Telerik.WinControls.UI.RadListDataItem(c) { Image = new Bitmap(Properties.Resources._006) });
            //}
        }

       

        

        private void OptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void MenuItemVideoEditing_Click(object sender, EventArgs e)
        {
                
        }

        private void 返回项目列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void 推出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            switch (pl_Experiment.Tag.ToString())
            {
                case "E"://由折叠状态变为展开
                    pl_Experiment.Width += 5;
                    Point p1 = pictureBox1.Location;
                    p1.X += 5;
                    pictureBox1.Location = p1;
                    if (pl_Experiment.Width >= 500)
                    {
                        timer1.Enabled = false;
                    }
                    break;
                case "C"://由展开状态变为折叠
                    pl_Experiment.Width -= 5;
                    Point p2 = pictureBox1.Location;
                    p2.X -= 5;
                    pictureBox1.Location = p2;
                    if (pl_Experiment.Width <= 30)
                    {
                        timer1.Enabled = false;
                    }
                    break;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            
            if (pl_Experiment.Tag.Equals("C"))
            {
                pictureBox1.Image = new Bitmap(Properties.Resources.收缩);
                pl_Experiment.Tag = "E";

            }
            else
            {
                pictureBox1.Image = new Bitmap(Properties.Resources.Expand);
                pl_Experiment.Tag = "C";
            }
            timer1.Enabled = true;
        }

        private void checkCh5_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as CheckBox).CheckState == CheckState.Checked)
            {
                groupBox1.Visible = false;
                groupBox2.Visible = false;
                groupBox3.Visible = false;
                groupBox4.Visible = false;
                groupBox5.Visible = true;
                checkCh1.Checked = false;
                checkCh2.Checked = false;
                checkCh3.Checked = false;
                checkCh4.Checked = false;
            }
        }

        private void checkCh1_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            if (cb.Checked == true)
            {
                groupBox5.Visible = false;
                groupBox1.Visible = true;
                groupBox2.Visible = true;
                groupBox3.Visible = true;
                groupBox4.Visible = true;
                checkCh5.Checked = false;
            }
          
        }

        private void 开始试验ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TestItems ti = new TestItems(_ProjectID);
            ti.FormClosed += new FormClosedEventHandler(ti_FormClosed);
            DialogResult dr = ti.ShowDialog(this);
        }

        string _TestKind = string.Empty;
        void ti_FormClosed(object sender, FormClosedEventArgs e)
        {            
            TestItems item = sender as TestItems;
            if (item.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                _TestKind = item.TestItem;
                switch (_TestKind)
                {
                    case "zlTest":
                        Resistance resistanceDlg = new Resistance(_ProjectID);
                        DialogResult rsltResistance = resistanceDlg.ShowDialog(this);
                        if (rsltResistance == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(resistanceDlg.datas, _ProjectID, ExperimentType.阻力实验);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);

                        }
                        break;
                    case "zhTest":
                        Zihang zihangDlg = new Zihang(_ProjectID);
                        DialogResult rsltZihang = zihangDlg.ShowDialog(this);
                        if (rsltZihang == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(zihangDlg.result, _ProjectID, ExperimentType.自航实验);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "csTest":
                        Changshui changshuiDlg = new Changshui(_ProjectID);
                        DialogResult rsltChangshui = changshuiDlg.ShowDialog(this);
                        if (rsltChangshui == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(changshuiDlg.result, _ProjectID, ExperimentType.敞水试验);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "zxgzbLRWT":
                        LRWT lrwtDlg = new LRWT(_ProjectID);
                        DialogResult rsltLRWT = lrwtDlg.ShowDialog(this);
                        if (rsltLRWT == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(lrwtDlg.Combination, _ProjectID, ExperimentType.敞水试验);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "zxbgzbLIWT":
                        LIWT liwtDlg = new LIWT(_ProjectID);
                        DialogResult rsltLIWT = liwtDlg.ShowDialog(this);
                        if (rsltLIWT == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(liwtDlg.Combination, _ProjectID, ExperimentType.纵向不规则波LIWT);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "lshygzbRT":
                        RT rtDlg = new RT(_ProjectID);
                        DialogResult rsltRT = rtDlg.ShowDialog(this);
                        if (rsltRT == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(rtDlg.Combination, _ProjectID, ExperimentType.零速横摇规则波RT);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "lshybgzbRI":
                        RI riDlg = new RI(_ProjectID);
                        DialogResult rsltRI = riDlg.ShowDialog(this);
                        if (rsltRI == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(riDlg.Combination, _ProjectID, ExperimentType.零速横摇不规则波RI);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                    case "defualtRRT":
                        RRT rrtDlg = new RRT(_ProjectID);
                        DialogResult rsltRRT = rrtDlg.ShowDialog(this);
                        if (rsltRRT == System.Windows.Forms.DialogResult.OK)
                        {
                            TestData td = new TestData(rrtDlg.Combination, _ProjectID, ExperimentType.零速横摇不规则波RI);
                            td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                            td.ShowDialog(this);
                        }
                        break;
                }
            }
        }
        private ObservableCollection<ExperimentCombinationEntity> _Expert = new ObservableCollection<ExperimentCombinationEntity>();
        public ObservableCollection<ExperimentCombinationEntity> Expert
        {
            get { return _Expert; }
        }
        void td_FormClosed(object sender, FormClosedEventArgs e)
        {
            开始试验ToolStripMenuItem.Enabled = false;
            TestData td = sender as TestData;
            if (td != null && td.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                //ExItemsList.Items.Clear();
                foreach (var c in td.result)
                {
                    Expert.Add(c);
                }
                //ExItemsList.Items.Add(new Telerik.WinControls.UI.RadListDataItem() { Text =  });
                //foreach(var c in )
            }
        }

        private void btn_Edit_Click(object sender, EventArgs e)
        {
            if (ExItemsList.SelectedItems.Count > 0)
            {
                for (int i = 0; i < ExItemsList.SelectedItems.Count; i++ )
                {
                    var c = ExItemsList.SelectedItems[i];
                    ExperimentCombinationEntity entity = c.Value as ExperimentCombinationEntity;
                    if (c != null)
                    {
                        TestData td = new TestData(
                           entity.ID, entity.ProjectID, (ExperimentType)Enum.Parse(typeof(ExperimentType), entity.ExperimentType));
                        Expert.Remove(entity);
                        td.FormClosed += new FormClosedEventHandler(td_FormClosed);
                        td.Show(this);                       

                    }
                }
            }
            else
            {
                MessageBox.Show("请选择编辑项!");
            }
            //if (ExItemsList.SelectedItem != null)
            //{
            //    Telerik.WinControls.UI.RadListDataItem item = ExItemsList.SelectedItem;
            //    item.Image = new Bitmap(Properties.Resources._007);

            //}
        }
        /// <summary>
        /// 四路合并
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            groupBox1.Visible = false;
            groupBox2.Visible = false;
            groupBox3.Visible = false;
            groupBox4.Visible = false;
            groupBox5.Visible = true;
            InitailVedio(true);
        }


        /// <summary>
        /// 四路独立
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            groupBox5.Visible = false;
            groupBox1.Visible = true;
            groupBox2.Visible = true;
            groupBox3.Visible = true;
            groupBox4.Visible = true;
            InitailVedio(false);
        }

        int timeElapsed;
        private int currentTestComb = 1;
        void StopCapture(DataTypes.TestCombinationInfo testInfo)
        {
            HikVisionSDK.StopVideoCapture(Ch1);
            HikVisionSDK.StopVideoCapture(Ch2);
            HikVisionSDK.StopVideoCapture(Ch3);
            HikVisionSDK.StopVideoCapture(Ch4);
            HikVisionSDK.StopVideoCapture(Ch5);
            //timer1.Stop();

            if (btnStartCapture.InvokeRequired)
            {
                this.Invoke(new SetButtonEnableCallback(() =>
                {
                    btnStartCapture.
                        Enabled =
                        true;
                    btnStartCapture.Focus();
                }));
            }

            if (recStatusLight.InvokeRequired)
            {
                this.Invoke(new SetRecStatusLightPicCallback(() =>
                {
                    recStatusLight.Enabled = false;
                    recStatusLight.Image = Properties.Resources.red_dark;
                    recStatusLight.Refresh();
                }));
            }

            if (lblTimeElapsed.InvokeRequired)
            {
                this.Invoke(new SetlblTimeElapsedCallback(() =>
                {
                    lblTimeElapsed.Text = "";
                }));
            }



            //recStatusLight.Enabled = false;
            //button3.Enabled = true;
            timeElapsed = 0;
            currentTestComb++;

            testInfo.Done = true;
            testInfo.Date = DateTime.Today;
            testInfo.DiskPath = _VideoPicPath;
            //DbAccess.UpdateTestCombination(testInfo);



        }

        private bool _IsREC = false;
        public bool IsREC
        {
            get { return _IsREC; }
            set
            {
                _IsREC = value;
                //正在录像，禁用checkbox 和开始按钮及 预览按钮

                checkCh1.Enabled = !_IsREC;
                checkCh2.Enabled = !_IsREC;
                checkCh3.Enabled = !_IsREC;
                checkCh4.Enabled = !_IsREC;
                checkCh5.Enabled = !_IsREC;
                btnStartCapture.Enabled = !_IsREC;
                button1.Enabled = !_IsREC;
                button2.Enabled = !_IsREC;                
            }
        }

        /// <summary>
        /// 开始录像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartCapture_Click(object sender, EventArgs e)
        {
            //判断是否有视频被勾上
            if (checkCh1.Checked == false && checkCh2.Checked == false && checkCh3.Checked == false && checkCh4.Checked == false && checkCh5.Checked == false)
            {
                MessageBox.Show("未选中任何视频，无法录像!");
                return;
            }
            InitailVedio(checkCh5.Checked);
            #region orignal
            recStatusLight.Image = Properties.Resources.red_bl;
            recStatusLight.Enabled = true;
            timer2.Start();
            StartTime = DateTime.Now;
            Task.Factory.StartNew(
                             (o) =>
                             {
                                 DataTypes.TestCombinationInfo testInfo = new DataTypes.TestCombinationInfo();

                                 try
                                 {

                                 }
                                 catch (ArgumentOutOfRangeException ex)
                                 {
                                     StopCapture(testInfo);
                                     TestCombinationInfos.Clear();
                                     currentTestComb = 1;
                                     MessageBox.Show("已选试验数据录制完毕。");
                                     return;
                                 }


                                 testInfo.ToDo = true;
                                 if (testInfo.ToDo)
                                 {
                                     _VideoPicPath = GetDirectory();

                                     DirectoryInfo dir =
                                         new DirectoryInfo(_VideoPicPath);
                                     if (!dir.Exists)
                                     {
                                         dir.Create();
                                     }

                                     _picPath = _VideoPicPath;

                                     _startTime = DateTime.Now;
                                     bool[] chs = GetCaptureCh();
                                     CaptureVideo(chs);

                                     testInfo.Doing = true;
                                 }

                             },
                      this);
            #endregion

            IsREC = true;

        }

        void CaptureVideo(bool[] chs)
        {


            //HikVisionSDK.StartVideoCapture(Ch1);
            //HikVisionSDK.StartVideoCapture(Ch2);
            //HikVisionSDK.StartVideoCapture(Ch3);
            //HikVisionSDK.StartVideoCapture(Ch4);
            //HikVisionSDK.StartVideoCapture(Ch5);
            uint i = 0;
            int result = 0;
            foreach (bool ch in chs)
            {
                i++;
                if (ch)
                {
                    switch (i)
                    {
                        case 1:
                           result =  HikVisionSDK.StartVideoCapture(Ch1);

                            break;
                        case 2:

                            result = HikVisionSDK.StartVideoCapture(Ch2);

                            break;
                        case 3:

                            result = HikVisionSDK.StartVideoCapture(Ch3);
                            break;
                        case 4:
                            result = HikVisionSDK.StartVideoCapture(Ch4);

                            break;
                        case 5:
                            //HikVisionSDK.StartVideoCapture(Ch1);
                            //HikVisionSDK.StartVideoCapture(Ch2);
                            //HikVisionSDK.StartVideoCapture(Ch3);
                            //HikVisionSDK.StartVideoCapture(Ch4);
                            result = HikVisionSDK.StartVideoCapture(Ch5);

                            break;

                    }

                }


            }
            //timer1.Start();

        }

        /// <summary>
        /// 停止录像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopCapture_Click(object sender, EventArgs e)
        {
            timer2.Stop();
            StopCapture(CurrentTestCombInfo);
            //HikVisionSDK.DeInitDSPs();
            btnStartCapture.Enabled = true;
            btnStartCapture.Focus();
            lblTimeElapsed.Text = "     ";
            recStatusLight.Enabled = false;
            recStatusLight.Image = Properties.Resources.red_dark;
            recStatusLight.Refresh();

            //lblPreTestData.Text = lblCurTestData.Text;
            //lblCurTestData.Text = "   ";

            timeElapsed = 0;

            bStopped = true;
            IsREC = false;
        }

        private void btnTestData_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Explorer.exe", this.GetDirectory());
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (ExItemsList.SelectedItems.Count > 0)
            {
                for (int i = 0; i < ExItemsList.SelectedItems.Count; i++ )
                {
                    var c = ExItemsList.SelectedItems[i];
                    ExperimentCombinationEntity entity = c.Value as ExperimentCombinationEntity;
                    if (c != null)
                    {
                        Expert.Remove(entity);

                    }
                }
            }
            else
            {
                MessageBox.Show("请选择删除项!");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (ExItemsList.SelectedItems.Count > 0)
            {
                for (int i = 0; i < ExItemsList.SelectedItems.Count; i++ )
                {
                    var c = ExItemsList.SelectedItems[i];
                    int index = ExItemsList.Items.IndexOf(c);
                    ExItemsList.Items.Remove(c);
                    index = index - 1 >= 0 ? index-1 : 0;
                    ExItemsList.Items.Insert(index, c);
                }
            }
            else
            {
                MessageBox.Show("请选择移动项!");
            }
        }

        /// <summary>
        /// 更改实验项状态，并同时更新到数据库中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExItemsList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            CommonModel model = null;
            foreach (var c in ExItemsList.SelectedItems)
            {
                model = new CommonModel();
                ExperimentCombinationEntity entity = c.Value as ExperimentCombinationEntity;
                if (entity.IsIng.Equals("否") && entity.IsFinished.Equals("否"))
                {
                    int count = Expert.Where(d => d.IsIng.Equals("是")).Count();
                    if (count == 0)
                    {
                        entity.IsIng = "是";
                        c.Image = new Bitmap(Properties.Resources._006);
                    }
                    else
                    {
                        MessageBox.Show("不能两个实验项同时进行!");
                        return;
                    }
                }
                else if (entity.IsIng.Equals("是") && entity.IsFinished.Equals("否"))
                {
                    entity.IsIng = "否";
                    entity.IsFinished = "是";
                    c.Image = new Bitmap(Properties.Resources._007);
                }
                else
                {
                    entity.IsIng = "否";
                    entity.IsFinished = "否";
                    c.Image = new Bitmap(Properties.Resources._004);
                }
                model.Update<ExperimentCombinationEntity>(entity);
            }
            if (model != null)
                model = null;
        }



        public IntPtr Ch1;
        public IntPtr Ch2;
        public IntPtr Ch3;
        public IntPtr Ch4;
        public IntPtr Ch5;
        private bool InitailVedio(bool IsCombinedVideo)
        {
            try
            {
                int nChannels = HikVisionSDK.InitDSPs();
                //Debug.WriteLine("dsps{0}", nChannels);
                //this.Text = nChannels.ToString();
                uint nDispalyCh = HikVisionSDK.GetDisplayChannelCount();
                //Debug.WriteLine("disCh:{0}", nDispalyCh);
                DS_BOARD_DETAIL boardDetail = new DS_BOARD_DETAIL();

                Ch1 = HikVisionSDK.ChannelOpen(0);
                Ch2 = HikVisionSDK.ChannelOpen(1);
                Ch3 = HikVisionSDK.ChannelOpen(2);
                Ch4 = HikVisionSDK.ChannelOpen(3);
                Ch5 = HikVisionSDK.ChannelOpen(4);

                int rsltHikSDK = HikVisionSDK.SetEncoderPictureFormat(Ch1, PictureFormat_t.ENC_4CIF_FORMAT);
                rsltHikSDK = HikVisionSDK.SetEncoderPictureFormat(Ch2, PictureFormat_t.ENC_4CIF_FORMAT);
                rsltHikSDK = HikVisionSDK.SetEncoderPictureFormat(Ch3, PictureFormat_t.ENC_4CIF_FORMAT);
                rsltHikSDK = HikVisionSDK.SetEncoderPictureFormat(Ch4, PictureFormat_t.ENC_4CIF_FORMAT);
                rsltHikSDK = HikVisionSDK.SetEncoderPictureFormat(Ch5, PictureFormat_t.ENC_4CIF_FORMAT);

                HikVisionSDK.SetBitrateControlMode(Ch1, BitrateControlType_t.brVBR);
                HikVisionSDK.SetBitrateControlMode(Ch2, BitrateControlType_t.brVBR);
                HikVisionSDK.SetBitrateControlMode(Ch3, BitrateControlType_t.brVBR);
                HikVisionSDK.SetBitrateControlMode(Ch4, BitrateControlType_t.brVBR);
                HikVisionSDK.SetBitrateControlMode(Ch5, BitrateControlType_t.brVBR);

                HikVisionSDK.SetStreamType(Ch1, 1);
                HikVisionSDK.SetStreamType(Ch2, 1);
                HikVisionSDK.SetStreamType(Ch3, 1);
                HikVisionSDK.SetStreamType(Ch4, 1);
                HikVisionSDK.SetStreamType(Ch5, 1);

                HikVisionSDK.SetDefaultQuant(Ch1, 12, 12, 12);
                HikVisionSDK.SetDefaultQuant(Ch2, 12, 12, 12);
                HikVisionSDK.SetDefaultQuant(Ch3, 12, 12, 12);
                HikVisionSDK.SetDefaultQuant(Ch4, 12, 12, 12);
                HikVisionSDK.SetDefaultQuant(Ch5, 12, 12, 12);
                //HikVisionSDK.SetupBitrateControl(Ch1, 20480);
                // 
                //HikVisionSDK.SetupBitrateControl(Ch2, 20480);
                //HikVisionSDK.SetupBitrateControl(Ch3, 20480);
                //HikVisionSDK.SetupBitrateControl(Ch4, 20480);
                //HikVisionSDK.SetupBitrateControl(Ch5, 20480);

                //Debug.WriteLine("SetEncoderPicFormat:{0}", rsltHikSDK);
                ushort streamType = 0;
                HikVisionSDK.GetStreamType(Ch1, ref streamType);
                Rectangle rect1 = groupBox1.ClientRectangle; //new Rectangle(panel1.ClientRectangle.X, panel1.ClientRectangle.Y, panel1.Size.Width, panel1.Size.Height);
                Rectangle rect2 = groupBox2.ClientRectangle;//new Rectangle(panel2.ClientRectangle.X, panel2.ClientRectangle.Y, panel2.Size.Width, panel2.Size.Height);
                Rectangle rect3 = groupBox3.ClientRectangle;//new Rectangle(panel3.ClientRectangle.X, panel3.ClientRectangle.Y, panel3.Size.Width, panel3.Size.Height);
                Rectangle rect4 = groupBox4.ClientRectangle;//new Rectangle(panel4.ClientRectangle.X, panel4.ClientRectangle.Y, panel4.Size.Width, panel4.Size.Height);
                Rectangle rect5 = groupBox5.ClientRectangle;
                HikVisionSDK.RegisterStreamDirectReadCallback(streamDrctRdCallBack, this.Handle);
                if (IsCombinedVideo)
                {

                    //panel1.Hide();
                    //panel2.Hide();
                    //panel3.Hide();
                    //panel4.Hide();

                    //videoPanel.Refresh();

                    HikVisionSDK.StartVideoPreview(Ch5, groupBox5.Handle, ref rect5, true, 0, 30);



                    this.Refresh();

                }
                else
                {


                    //panel1.Show();
                    //panel2.Show();
                    //panel3.Show();
                    //panel4.Show();

                    //videoPanel.Refresh();

                    HikVisionSDK.StartVideoPreview(Ch1, groupBox1.Handle, ref rect1, true, 0, 30);
                    HikVisionSDK.StartVideoPreview(Ch2, groupBox2.Handle, ref rect2, true, 0, 30);
                    HikVisionSDK.StartVideoPreview(Ch3, groupBox3.Handle, ref rect3, true, 0, 30);
                    HikVisionSDK.StartVideoPreview(Ch4, groupBox4.Handle, ref rect4, true, 0, 30);

                    this.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        //获得文件录制路径
        private string GetDirectory()
        {
            string path = "d:\\SWAData\\";
            //path = path.Substring(0, path.Length - 18);
            path += pe.ProjectNo + "\\";
            var entity = Expert.Where(c => c.IsIng.Equals("是")).FirstOrDefault();
            if (entity == null)
                path += "空类型" + "\\";
            else
            {
                string dir = entity.DataCombination.Replace(":","");
                dir = dir.Replace(";","\\");
                path += entity.ExperimentType + "\\" + dir;
            }
            return path + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
        }

        bool[] GetCaptureCh()
        {
            bool[] chs = new bool[5] { false, false, false, false, false };

            if (checkCh1.Checked)
                chs[0] = true;
            else
                chs[0] = false;

            if (checkCh2.Checked)
                chs[1] = true;
            else
                chs[1] = false;

            if (checkCh3.Checked)
                chs[2] = true;
            else
                chs[2] = false;

            if (checkCh4.Checked)
                chs[3] = true;
            else
                chs[3] = false;

            if (checkCh5.Checked)
                chs[4] = true;
            else
                chs[4] = false;

            return chs;
        }


        #region CammeraAction

        #region  Event
        public EdsStateEventHandler stateEventHandler = delegate(uint inEvent, uint inParams, IntPtr inContext)
        {
            switch (inEvent)
            {
                case EDSDK.StateEvent_CaptureError:
                    MessageBox.Show("相机尚未准备好。");
                    break;
                default:
                    break;
            }
            return 0;
        };

        public EdsObjectEventHandler objectEventHandler =
            delegate(uint inEvent, IntPtr inRef, IntPtr inContext)
            {
                switch (inEvent)
                {
                    // in case of a download request
                    case
                        EDSDK.ObjectEvent_DirItemRequestTransfer
                        :
                        DownloadImage(inRef, _picPath, inContext);
                        Console.WriteLine(
                            "Directory Item Created");
                        break;
                    case EDSDK.ObjectEvent_DirItemCreated:
                        //this.invokeNewItemCreatedEvent(new NewItemCreatedEventArgs(getCapturedItem(inRef)));
                        Console.WriteLine(
                            "Directory Item Created");
                        break;
                    default:
                        Console.WriteLine(
                            String.Format(
                                "ObjectEventHandler: event {0}, ref {1}",
                                inEvent.ToString("X"),
                                inRef.ToString()));
                        break;

                }
                return EDSDK.EDS_ERR_OK;
            };

        public EdsObjectEventHandler objectEventHandler1 =
           delegate(uint inEvent, IntPtr inRef, IntPtr inContext)
           {
               switch (inEvent)
               {
                   // in case of a download request
                   case
                       EDSDK.ObjectEvent_DirItemRequestTransfer
                       :
                       DownloadImage(inRef, _picPath, inContext);
                       Console.WriteLine(
                           "Directory Item Created");
                       break;
                   case EDSDK.ObjectEvent_DirItemCreated:
                       //this.invokeNewItemCreatedEvent(new NewItemCreatedEventArgs(getCapturedItem(inRef)));
                       Console.WriteLine(
                           "Directory Item Created");
                       break;
                   default:
                       Console.WriteLine(
                           String.Format(
                               "ObjectEventHandler: event {0}, ref {1}",
                               inEvent.ToString("X"),
                               inRef.ToString()));
                       break;

               }
               return EDSDK.EDS_ERR_OK;
           };

        public EdsObjectEventHandler objectEventHandler2 =
           delegate(uint inEvent, IntPtr inRef, IntPtr inContext)
           {
               switch (inEvent)
               {
                   // in case of a download request
                   case
                       EDSDK.ObjectEvent_DirItemRequestTransfer
                       :
                       DownloadImage(inRef, _picPath, inContext);
                       Console.WriteLine(
                           "Directory Item Created");
                       break;
                   case EDSDK.ObjectEvent_DirItemCreated:
                       //this.invokeNewItemCreatedEvent(new NewItemCreatedEventArgs(getCapturedItem(inRef)));
                       Console.WriteLine(
                           "Directory Item Created");
                       break;
                   default:
                       Console.WriteLine(
                           String.Format(
                               "ObjectEventHandler: event {0}, ref {1}",
                               inEvent.ToString("X"),
                               inRef.ToString()));
                       break;

               }
               return EDSDK.EDS_ERR_OK;
           };

        private void btnCameraPreview_Click(object sender, EventArgs e)
        {
            #region 注册
            if (IsCamera1Inited && IsCamera2Inited && IsCamera2Inited)
            {
                MessageBox.Show("相机已经注册完毕!");
                return;
            }
            if (!IsCamera1Inited)
                InitCamera(0);

            if (!IsCamera2Inited)
                InitCamera(1);

            if (!IsCamera3Inited)
                InitCamera(2);
            #endregion
            #region 预览
            //isCameraPreview = true;
            //if (!IsCamera1Inited)
            //    InitCamera(0);

            //if (!IsCamera2Inited)
            //    InitCamera(1);

            //if (!IsCamera3Inited)
            //    InitCamera(2);

            //if (err1 == EDSDK.EDS_ERR_OK && err2 == EDSDK.EDS_ERR_OK && err3 == EDSDK.EDS_ERR_OK)
            //{
               
            //    if (ptrCamera != IntPtr.Zero || ptrCamera1 != IntPtr.Zero || ptrCamera2 != IntPtr.Zero)
            //    {

                   
            //        EDSDK.EdsCapacity cap = new EDSDK.EdsCapacity();

            //        uint SectorsPerCluster;
            //        uint BytesPerSector;
            //        uint NoOfFreeClusters;
            //        uint NoOfTotalClusters;

            //        Utils.GetDiskFreeSpace("d:", out SectorsPerCluster, out BytesPerSector, out NoOfFreeClusters,
            //                               out NoOfTotalClusters);
            //        cap.BytesPerSector = (int)BytesPerSector;
            //        cap.NumberOfFreeClusters = (int)NoOfFreeClusters;
            //        cap.Reset = 1;
            //        err1 = EDSDK.EdsSetCapacity(ptrCamera, cap);
            //        err1 = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);

            //        err2 = EDSDK.EdsSetCapacity(ptrCamera1, cap);
            //        err2 = EDSDK.EdsSetPropertyData(ptrCamera1, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);

            //        err3 = EDSDK.EdsSetCapacity(ptrCamera2, cap);
            //        err3 = EDSDK.EdsSetPropertyData(ptrCamera2, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);

            //        // We don't want to save pictures to the camera so lets set save target to host
            //        //err = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, 4, 2);
            //        //uint setsaveto =  EDSDK.EdsSaveTo.Both;

            //        if (err1 == EDSDK.EDS_ERR_OK)
            //        {
                        
            //            err1 = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_TakePicture, 0);

            //            if (err1 != EDSDK.EDS_ERR_OK)
            //                MessageBox.Show("相机1错误。");
            //        }

            //        if (err2 == EDSDK.EDS_ERR_OK)
            //        {
            //            err2 = EDSDK.EdsSendCommand(ptrCamera1, EDSDK.CameraCommand_TakePicture, 0);

            //            if (err2 != EDSDK.EDS_ERR_OK)
            //                MessageBox.Show("相机2错误。");
            //        }

            //        if (err3 == EDSDK.EDS_ERR_OK)
            //        {
            //            err3 = EDSDK.EdsSendCommand(ptrCamera2, EDSDK.CameraCommand_TakePicture, 0);

            //            if (err3 != EDSDK.EDS_ERR_OK)
            //                MessageBox.Show("相机2错误。");
            //        }

                    
            //    }
            //}
            //err1 = EDSDK.EDS_ERR_OK;
            //err2 = EDSDK.EDS_ERR_OK;
            //err3 = EDSDK.EDS_ERR_OK;

            //CameraPreview camPreview1 = new CameraPreview();
            //CameraPreview camPreview2 = new CameraPreview();

            //camPreview1.ShowDialog(this);
            //camPreview2.ShowDialog(this);
            #endregion
        }

        #endregion
        private static string _picPath = null;
        static private bool isCameraPreview = false;
        private static uint _whichCam = 1;
        public uint WhichCam
        {
            get { return _whichCam; }
            set { _whichCam = value; }
        }

        static private string _previewPic1 = @"c:\p1.jpg";
        public string PreviewPic1
        {
            get { return _previewPic1; }
            set { _previewPic1 = value; }
        }



        static private string _previewPic2 = @"c:\p2.jpg";
        public string PreviewPic2
        {
            get { return _previewPic2; }
            set { _previewPic2 = value; }
        }
        static private string _previewPic3 = @"c:\p3.jpg";
        public string PreviewPic3
        {
            get { return _previewPic3; }
            set { _previewPic3 = value; }
        }

        private static Form _mainHandler;
        public Form MainHandler
        {
            get { return _mainHandler; }
            set { _mainHandler = value; }
        }

        static private uint DownloadImage(IntPtr dItem, string path, IntPtr inContext)
        {

            EDSDK.EdsDirectoryItemInfo dirInfo;
            uint err;
            IntPtr stream = new IntPtr();
            err = EDSDK.EdsGetDirectoryItemInfo(dItem, out dirInfo);
            string photopath = "";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            } 


            if (err == EDSDK.EDS_ERR_OK)
            {
                if (isCameraPreview)
                {
                    
                    if (inContext == ptrCamera)
                    {
                        _whichCam = 1;
                        photopath = @"c:\p1.jpg";
                        err = EDSDK.EdsCreateFileStream(@"c:\p1.jpg", EDSDK.EdsFileCreateDisposition.CreateAlways,
                                                        EDSDK.EdsAccess.ReadWrite, out stream);

                    }
                    else if (inContext == ptrCamera1)
                    {
                        _whichCam = 2;
                        photopath = @"c:\p2.jpg";
                        err = EDSDK.EdsCreateFileStream(@"c:\p2.jpg", EDSDK.EdsFileCreateDisposition.CreateAlways,
                                                        EDSDK.EdsAccess.ReadWrite, out stream);

                    }
                    else if (inContext == ptrCamera2)
                    {
                        _whichCam = 3;
                        photopath = @"c:\p3.jpg";
                        err = EDSDK.EdsCreateFileStream(@"c:\p3.jpg", EDSDK.EdsFileCreateDisposition.CreateAlways,
                                                        EDSDK.EdsAccess.ReadWrite, out stream);
                        
                    }
                    //System.Diagnostics.Process.Start("Explorer.exe", photopath);
                    
                    

                }
                else
                {
                    
                    err = EDSDK.EdsCreateFileStream(path + dirInfo.szFileName,
                                                    EDSDK.EdsFileCreateDisposition.CreateAlways,
                                                    EDSDK.EdsAccess.ReadWrite, out stream);
                    //System.Diagnostics.Process.Start("Explorer.exe", path + dirInfo.szFileName);
                    //Form f = new Form() { BackgroundImage = new Bitmap(path + dirInfo.szFileName) };
                    //f.ShowDialog();

                    photopath = path + dirInfo.szFileName;
                }
            }
            if (err == EDSDK.EDS_ERR_OK)
            {
                err = EDSDK.EdsDownload(dItem, dirInfo.Size, stream);
            }
            if (err == EDSDK.EDS_ERR_OK)
            {
                err = EDSDK.EdsDownloadComplete(dItem);               
            }
            if (err == EDSDK.EDS_ERR_OK)
            {
                string destpath = @"d:\caches\"+DateTime.Now.Millisecond+".jpg";
                //File.Copy(photopath, destpath, true);
                //CameraPreview cp = new CameraPreview(destpath);
                //cp.ShowDialog();
            }
            if (stream != null)
            {
                EDSDK.EdsRelease(stream);
            }
            return err;
        }

        uint errAll = EDSDK.EDS_ERR_OK, err1 = EDSDK.EDS_ERR_OK, err2 = EDSDK.EDS_ERR_OK, err3 = EDSDK.EDS_ERR_OK;
        static IntPtr ptrCameraList, ptrCamera, ptrCamera1, ptrCamera2;        
        private bool IsCamera1Inited = false;
        private bool IsCamera2Inited = false;
        private bool IsCamera3Inited = false;
        int GetCameras(out IntPtr pCameraList)
        {
            //uint err = EDSDK.EDS_ERR_OK;

            errAll = EDSDK.EdsGetCameraList(out pCameraList);
            if (errAll == EDSDK.EDS_ERR_OK)
            {
                int nCount;
                errAll = EDSDK.EdsGetChildCount(ptrCameraList, out nCount);
                if (nCount == 0)
                {
                    MessageBox.Show("未找到相机。", "EOS_ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    errAll = EDSDK.EDS_ERR_DEVICE_NOT_FOUND;
                }
                return nCount;

            }
            return 0;
        }

        private int InitCamera(int camer)
        {
            errAll = EDSDK.EDS_ERR_OK;
            errAll = EDSDK.EdsInitializeSDK();
            _picPath = GetDirectory() + "Photo\\";
            int count = GetCameras(out ptrCameraList);
            if (count <= 0)
                return 0;
            switch (camer)
            {
                case 0:
                    err1 = EDSDK.EdsGetChildAtIndex(ptrCameraList, 0, out ptrCamera);
                    if (ptrCamera != IntPtr.Zero)
                        err1 = EDSDK.EdsSetObjectEventHandler(ptrCamera, EDSDK.ObjectEvent_All, objectEventHandler, ptrCamera);
                    if (ptrCamera != IntPtr.Zero)
                        err1 = EDSDK.EdsSetCameraStateEventHandler(ptrCamera, EDSDK.StateEvent_All, stateEventHandler,
                                                                  IntPtr.Zero);
                    if (ptrCamera != IntPtr.Zero)
                        err1 = EDSDK.EdsOpenSession(ptrCamera);
                    if (ptrCamera != IntPtr.Zero && err1 == EDSDK.EDS_ERR_OK)
                        err1 = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_Evf_OutputDevice, 0,
                                                       (int)EDSDK.EdsDataType.UInt32, EDSDK.EvfOutputDevice_TFT);
                    if (ptrCamera != IntPtr.Zero && err1 == EDSDK.EDS_ERR_OK)
                        err1 = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_ExtendShutDownTimer, 0);
                    if (errAll == EDSDK.EDS_ERR_OK && err1 != EDSDK.EDS_ERR_OK)
                    {
                        MessageBox.Show("无法注册相机1!");
                        err1 = EDSDK.EDS_ERR_UNEXPECTED_EXCEPTION;
                    }
                    if (errAll == EDSDK.EDS_ERR_OK && err1 == EDSDK.EDS_ERR_OK)
                        IsCamera1Inited = true;
                    break;

                case 1:
                    err2 = EDSDK.EdsGetChildAtIndex(ptrCameraList, 1, out ptrCamera1);
                    if (ptrCamera1 != IntPtr.Zero)
                        err2 = EDSDK.EdsSetObjectEventHandler(ptrCamera1, EDSDK.ObjectEvent_All, objectEventHandler1, ptrCamera1);
                    if (ptrCamera1 != IntPtr.Zero)
                        err2 = EDSDK.EdsSetCameraStateEventHandler(ptrCamera1, EDSDK.StateEvent_All, stateEventHandler,
                                                      IntPtr.Zero);
                    if (ptrCamera1 != IntPtr.Zero)
                        err2 = EDSDK.EdsOpenSession(ptrCamera1);
                    if (ptrCamera1 != IntPtr.Zero && err2 == EDSDK.EDS_ERR_OK)
                        err2 = EDSDK.EdsSetPropertyData(ptrCamera1, EDSDK.PropID_Evf_OutputDevice, 0,
                                                    (int)EDSDK.EdsDataType.UInt32, EDSDK.EvfOutputDevice_TFT);
                    if (ptrCamera1 != IntPtr.Zero && err2 == EDSDK.EDS_ERR_OK)
                        err2 = EDSDK.EdsSendCommand(ptrCamera1, EDSDK.CameraCommand_ExtendShutDownTimer, 0);
                    if (errAll == EDSDK.EDS_ERR_OK && err2 != EDSDK.EDS_ERR_OK)
                    {
                        MessageBox.Show("无法注册相机2!");
                        err2 = EDSDK.EDS_ERR_UNEXPECTED_EXCEPTION;
                    }
                    if (errAll == EDSDK.EDS_ERR_OK && err2 == EDSDK.EDS_ERR_OK)
                        IsCamera2Inited = true;

                    break;
                case 2:
                    err3 = EDSDK.EdsGetChildAtIndex(ptrCameraList, 2, out ptrCamera2);
                    if (ptrCamera2 != IntPtr.Zero)
                        err3 = EDSDK.EdsSetObjectEventHandler(ptrCamera2, EDSDK.ObjectEvent_All, objectEventHandler2, ptrCamera2);
                    if (ptrCamera2 != IntPtr.Zero)
                        err3 = EDSDK.EdsSetCameraStateEventHandler(ptrCamera2, EDSDK.StateEvent_All, stateEventHandler,
                                                      IntPtr.Zero);
                    if (ptrCamera2 != IntPtr.Zero)
                        err3 = EDSDK.EdsOpenSession(ptrCamera2);
                    if (ptrCamera1 != IntPtr.Zero && err3 == EDSDK.EDS_ERR_OK)
                        err3 = EDSDK.EdsSetPropertyData(ptrCamera2, EDSDK.PropID_Evf_OutputDevice, 0,
                                                    (int)EDSDK.EdsDataType.UInt32, EDSDK.EvfOutputDevice_TFT);
                    if (ptrCamera2 != IntPtr.Zero && err3 == EDSDK.EDS_ERR_OK)
                        err3 = EDSDK.EdsSendCommand(ptrCamera2, EDSDK.CameraCommand_ExtendShutDownTimer, 0);
                    if (errAll == EDSDK.EDS_ERR_OK && err3 != EDSDK.EDS_ERR_OK)
                    {
                        MessageBox.Show("无法注册相机3!");
                        err3 = EDSDK.EDS_ERR_UNEXPECTED_EXCEPTION;
                    }
                    if (errAll == EDSDK.EDS_ERR_OK && err3 == EDSDK.EDS_ERR_OK)
                        IsCamera3Inited = true;
                    break;
            }
            return count;
        
        }

        /// <summary>
        /// 相机1拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCam1_Click(object sender, EventArgs e)
        {
            isCameraPreview = false;
            if (!IsCamera1Inited)
            {
                InitCamera(0);              
            }

            if (err1 == EDSDK.EDS_ERR_OK)
            {
                //err = EDSDK.EdsGetChildAtIndex(ptrCameraList, 0, out ptrCamera);

                EDSDK.EdsDeviceInfo deviceInfo;
                if (ptrCamera != IntPtr.Zero)
                {
                    EDSDK.EdsCapacity cap = new EDSDK.EdsCapacity();

                    uint SectorsPerCluster;
                    uint BytesPerSector;
                    uint NoOfFreeClusters;
                    uint NoOfTotalClusters;

                    Utils.GetDiskFreeSpace("c:", out SectorsPerCluster, out BytesPerSector, out NoOfFreeClusters,
                                           out NoOfTotalClusters);
                    cap.BytesPerSector = (int)BytesPerSector;
                    cap.NumberOfFreeClusters = (int)NoOfFreeClusters;
                    cap.Reset = 1;
                    err1 = EDSDK.EdsSetCapacity(ptrCamera, cap);
                    err1 = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);


                    if (err1 == EDSDK.EDS_ERR_OK)
                    {
                        //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DoEvfAf, (int)EDSDK.EdsEvfAFMode.Evf_AFMode_Quick);
                        err1 = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_TakePicture, 0);
                        //err = EDSDK.EdsSendCommand(ptrCamera1, EDSDK.CameraCommand_TakePicture, 0);
                        if (err1 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机1暂时不能拍照。");
                        //else
                        //    lblPhotoStatus.Text = "已拍照";
                    }

                    //EDSDK.EdsCloseSession(ptrCamera);z
                }
            }

            err1 = EDSDK.EDS_ERR_OK;
        }

        /// <summary>
        /// 相机二拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCam2_Click(object sender, EventArgs e)
        {
            isCameraPreview = false;
            if (!IsCamera2Inited)
            {
                InitCamera(1);
                //IsCameraInited = true;
            }

            if (err2 == EDSDK.EDS_ERR_OK)
            {
                //err = EDSDK.EdsGetChildAtIndex(ptrCameraList, 0, out ptrCamera);

                EDSDK.EdsDeviceInfo deviceInfo;
                if (ptrCamera1 != IntPtr.Zero)
                {
                    //EDSDK.EdsGetDeviceInfo(ptrCamera, out deviceInfo);

                    //this.Title = deviceInfo.szDeviceDescription;
                    // Set object event handler, We need this event handler to retrieve pictures from camera
                    //  Register OBJECT events

                    //EDSDK.EdsObjectEventHandler edsObjectEventHandler = new EDSDK.EdsObjectEventHandler(CameraEventListener.handleObjectEvent);

                    //err = EDSDK.EdsSetObjectEventHandler(ptrCamera, EDSDK.ObjectEvent_All, edsObjectEventHandler, IntPtr.Zero);


                    //err = EDSDK.EdsOpenSession(ptrCamera);


                    //err = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_Evf_OutputDevice, 0, (int)EDSDK.EdsDataType.UInt32, EDSDK.EvfOutputDevice_TFT);
                    //err = EDSDK.EdsSendCommand(ptrCamera, (int)EDSDK.EdsEvfAf.CameraCommand_EvfAf_ON, 0);
                    // err = EDSDK.EdsSendStatusCommand(ptrCamera, EDSDK.CameraState_UIUnLock, 0);
                    //err = EDSDK.EdsSendStatusCommand(ptrCamera, EDSDK.CameraState_EnterDirectTransfer, 0);
                    if (err2 == EDSDK.EDS_ERR_OK)
                        // err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_ExtendShutDownTimer, 0);
                        if (err2 == EDSDK.EDS_ERR_OK)
                            //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DoEvfAf, (int)EDSDK.EdsEvfAFMode.Evf_AFMode_LiveFace);
                            if (err2 == EDSDK.EDS_ERR_OK)
                            {
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Far3);
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Near1);
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Far2);
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Near2);
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Far1);
                                //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DriveLensEvf, (int)EDSDK.EvfDriveLens_Near3);

                            }
                    EDSDK.EdsCapacity cap = new EDSDK.EdsCapacity();

                    uint SectorsPerCluster;
                    uint BytesPerSector;
                    uint NoOfFreeClusters;
                    uint NoOfTotalClusters;

                    Utils.GetDiskFreeSpace("d:", out SectorsPerCluster, out BytesPerSector, out NoOfFreeClusters,
                                           out NoOfTotalClusters);
                    cap.BytesPerSector = (int)BytesPerSector;
                    cap.NumberOfFreeClusters = (int)NoOfFreeClusters;
                    cap.Reset = 1;
                    //err = EDSDK.EdsSetCapacity(ptrCamera, cap);
                    //err = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);

                    err2 = EDSDK.EdsSetCapacity(ptrCamera1, cap);
                    err2 = EDSDK.EdsSetPropertyData(ptrCamera1, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);




                    // We don't want to save pictures to the camera so lets set save target to host
                    //err = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, 4, 2);
                    //uint setsaveto =  EDSDK.EdsSaveTo.Both;

                    if (err2 == EDSDK.EDS_ERR_OK)
                    {
                        //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DoEvfAf, (int)EDSDK.EdsEvfAFMode.Evf_AFMode_Quick);
                        //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_TakePicture, 0);
                        err2 = EDSDK.EdsSendCommand(ptrCamera1, EDSDK.CameraCommand_TakePicture, 0);

                        if (err2 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机2暂时不能拍照。");
                        else
                        {
                            //lblPhotoStatus.Text = "已拍照";
                        }
                    }

                    //EDSDK.EdsCloseSession(ptrCamera);z
                }
            }
            err2 = EDSDK.EDS_ERR_OK;

        }


        /// <summary>
        /// 相机三拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCam3_Click(object sender, EventArgs e)
        {
            isCameraPreview = false;
            if (!IsCamera3Inited)
            {
                InitCamera(2);
                //IsCameraInited = true;
            }

            if (err3 == EDSDK.EDS_ERR_OK)
            {
                //err = EDSDK.EdsGetChildAtIndex(ptrCameraList, 0, out ptrCamera);

                EDSDK.EdsDeviceInfo deviceInfo;
                if (ptrCamera2 != IntPtr.Zero)
                {
                    EDSDK.EdsCapacity cap = new EDSDK.EdsCapacity();

                    uint SectorsPerCluster;
                    uint BytesPerSector;
                    uint NoOfFreeClusters;
                    uint NoOfTotalClusters;

                    Utils.GetDiskFreeSpace("d:", out SectorsPerCluster, out BytesPerSector, out NoOfFreeClusters,
                                           out NoOfTotalClusters);
                    cap.BytesPerSector = (int)BytesPerSector;
                    cap.NumberOfFreeClusters = (int)NoOfFreeClusters;
                    cap.Reset = 1;
                

                    err3 = EDSDK.EdsSetCapacity(ptrCamera2, cap);
                    err3 = EDSDK.EdsSetPropertyData(ptrCamera2, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);



                    if (err3 == EDSDK.EDS_ERR_OK)
                    {
                     
                        err3 = EDSDK.EdsSendCommand(ptrCamera2, EDSDK.CameraCommand_TakePicture, 0);

                        if (err2 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机2暂时不能拍照。");
                        else
                        {
                            //lblPhotoStatus.Text = "已拍照";
                        }
                    }

                    //EDSDK.EdsCloseSession(ptrCamera);z
                }
            }
            err2 = EDSDK.EDS_ERR_OK;

        }

        /// <summary>
        /// 全部相机拍照
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllCams_Click(object sender, EventArgs e)
        {
            isCameraPreview = false;
            if (!IsCamera1Inited)
                InitCamera(0);

            if ( !IsCamera2Inited)
                InitCamera(1);

            if (!IsCamera3Inited)
                InitCamera(2);

            if (err1 == EDSDK.EDS_ERR_OK && err2 == EDSDK.EDS_ERR_OK && err3 == EDSDK.EDS_ERR_OK)
            {
                EDSDK.EdsDeviceInfo deviceInfo;
                
                    EDSDK.EdsCapacity cap = new EDSDK.EdsCapacity();

                    uint SectorsPerCluster;
                    uint BytesPerSector;
                    uint NoOfFreeClusters;
                    uint NoOfTotalClusters;

                    Utils.GetDiskFreeSpace("d:", out SectorsPerCluster, out BytesPerSector, out NoOfFreeClusters,
                                           out NoOfTotalClusters);
                    cap.BytesPerSector = (int)BytesPerSector;
                    cap.NumberOfFreeClusters = (int)NoOfFreeClusters;
                    cap.Reset = 1;
                    err1 = EDSDK.EdsSetCapacity(ptrCamera, cap);
                    err1 = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);

                    err2 = EDSDK.EdsSetCapacity(ptrCamera1, cap);
                    err2 = EDSDK.EdsSetPropertyData(ptrCamera1, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);
 
                    err3 = EDSDK.EdsSetCapacity(ptrCamera2, cap);
                    err3 = EDSDK.EdsSetPropertyData(ptrCamera2, EDSDK.PropID_SaveTo, 0, sizeof(uint), 2);




                    // We don't want to save pictures to the camera so lets set save target to host
                    //err = EDSDK.EdsSetPropertyData(ptrCamera, EDSDK.PropID_SaveTo, 0, 4, 2);
                    //uint setsaveto =  EDSDK.EdsSaveTo.Both;

                    if (err1 == EDSDK.EDS_ERR_OK && err2 == EDSDK.EDS_ERR_OK && err3 == EDSDK.EDS_ERR_OK)
                    {
                        //err = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_DoEvfAf, (int)EDSDK.EdsEvfAFMode.Evf_AFMode_Quick);
                        err1 = EDSDK.EdsSendCommand(ptrCamera, EDSDK.CameraCommand_TakePicture, 0);
                        err2 = EDSDK.EdsSendCommand(ptrCamera1, EDSDK.CameraCommand_TakePicture, 0);
                        err3 = EDSDK.EdsSendCommand(ptrCamera2, EDSDK.CameraCommand_TakePicture, 0);

                        if (err1 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机1错误。");

                        if (err2 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机2错误。");

                        if (err3 != EDSDK.EDS_ERR_OK)
                            MessageBox.Show("相机3错误。");

                        if (err1 == EDSDK.EDS_ERR_OK && err2 == EDSDK.EDS_ERR_OK && err3 == EDSDK.EDS_ERR_OK )
                            MessageBox.Show( "已拍照");
                    }

                    //EDSDK.EdsCloseSession(ptrCamera);z
                }
            }
           

        

        #endregion
        DirectoryInfo _DataDir = new DirectoryInfo(@"d:\\SWAData");
        public System.IO.DirectoryInfo DataDir
        {
            get { return _DataDir; }
            set { _DataDir = value; }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            string _burnerPath = Application.StartupPath + @"\ExtBin\BurnMedia.exe";
            Process p = new Process();
            p.StartInfo.FileName = _burnerPath;
            p.StartInfo.Arguments = DataDir.FullName;
            p.Start();
        }

        private void tbTimeLengh_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tbTimeLengh.ReadOnly = !tbTimeLengh.ReadOnly;
        }
        private DateTime StartTime = DateTime.Now;
        private void timer2_Tick(object sender, EventArgs e)
        {
            int length = (DateTime.Now - StartTime).Seconds;
            int Setting = int.Parse(tbTimeLengh.Text);
            if (length >= Setting)
            {
                btnStopCapture_Click(null, null);
            }
        }

        private void tbTimeLengh_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int Setting = int.Parse(tbTimeLengh.Text);
                if (Setting <= 0)
                    throw new Exception();
            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入整数秒！");
                tbTimeLengh.Text = 60 + "";
            }
        }


    }
}
